package com.yawn.zerodefect.controller;

import com.yawn.zerodefect.controller.entity.RestResponse;
import com.yawn.zerodefect.service.DefectService;
import com.yawn.zerodefect.util.WebUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Created by yawn on 2018-02-02 18:46
 */
@RestController
public class FileController {

    @Resource
    private DefectService defectService;

    private static final String FILE_ROOT_DIR = "D:/upload/zero-defect/";

    @PostMapping("/file/upload")
    public RestResponse upload(MultipartFile image, String guid, String taskId) throws IOException {
        File dir = new File(FILE_ROOT_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String originalFilename = image.getOriginalFilename();
        if (!originalFilename.contains(".")) {
            originalFilename = originalFilename + ".png";
        }
        String fileName = System.currentTimeMillis() + "_" + originalFilename;
        File file = new File(FILE_ROOT_DIR + fileName);
        file.createNewFile();
        image.transferTo(file);
        //
        if (!"undefined".equals(taskId)) {
            defectService.addAttachment(taskId, "/file/" + fileName);
        }

        Map<String, String> data = new HashMap<>();
        data.put("fileName", "/file/" + fileName);
        data.put("guid", guid);
        return RestResponse.newInstance(1, data);
    }

    @GetMapping("/file/{name}")
    public ResponseEntity<byte[]> getFile(@PathVariable String name) throws IOException {
        File pngFile = new File(FILE_ROOT_DIR + name + ".png");
        File jpgFile = new File(FILE_ROOT_DIR + name + ".jpg");
        File file = pngFile.exists() ? pngFile : jpgFile;
        return WebUtil.download(file);
    }
}
